from PySide2.QtWidgets import QApplication, QMessageBox, QLabel, QGraphicsScene
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QTimer
import numpy as np
import re
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
import matplotlib
from threading import Thread

matplotlib.use("Qt5Agg")  # 声明使用QT5


class MyFigureCanvas(FigureCanvas):
    """
    通过继承FigureCanvas类，使得该类既是一个PyQt5的Qwidget，又是一个matplotlib的FigureCanvas，这是连接pyqt5与matplotlib的关键
    """

    # def __init__(self, parent=None, width=10, height=5, xlim=(0, 2500), ylim=(-2, 2), dpi=100):
    def __init__(self, parent=None, width=12, height=12, dpi=90):
        # 初始化时将图片的长、宽、像素均初始化给定
        # 其中xlim，ylim 表示横纵坐标的显示范围
        # 创建一个Figure
        self.figure = plt.Figure(figsize=(width, height), dpi=dpi, tight_layout=True)  # tight_layout: 用于去除画图时两边的空白
        FigureCanvas.__init__(self, self.figure)  # 初始化父类
        self.setParent(parent)

        self.fig1 = self.figure.add_subplot(111)  # 添加子图
        # add_subplot(2,2,4) 添加子图函数，三个参数分别表示纵向分几个子图，横向分几个子图，当前为第几个子图
        self.fig1.spines['top'].set_visible(False)
        self.fig1.spines['right'].set_visible(False)
        # self.fig1.set_xlim(xlim)
        # self.fig1.set_ylim(ylim)


class MainWindow:

    def __init__(self):
        self.ui = QUiLoader().load('ui/graphics.ui')
        self.gv_visual_data_content = MyFigureCanvas(width=self.ui.graphicsView.width() / 100,
                                                     height=self.ui.graphicsView.height() / 100,
                                                     # xlim=(0, 2 * np.pi),
                                                     # ylim=(-1, 1)
                                                     )
        self.ui.pushButton.clicked.connect(self.Plot_line)



    def Plot_line(self):
        #颜色选择后续可改用色盘
        Line_Color = {'蓝色': 'b', '黑色': 'k', '绿色': 'g', '黄色': 'y', '红色': 'r', '白色': 'w', '洋红色': 'm',
                      '青绿色': 'c'}
        Line_type={'实线':'-','虚线':':','点划线':'-.','破折线':'--'}
        Symbol_mark={'无标记':'','圆点':'.','圆圈':'o','向下三角形':'v','向上三角形':'^','向左三角形':'<','向右三角形':'>','五角星形':'*','加号':'+',
                     '下划线':'_','x符号':'x','菱形':'D'}
        Color_text = self.ui.ColorboBox.currentText()
        Line_text=self.ui.LineboBox.currentText()
        Symbol_text=self.ui.SymbolboBox.currentText()
        Line_shape=Line_Color[Color_text]+Line_type[Line_text]+Symbol_mark[Symbol_text]

        Plot_title=self.ui.TitleextEdit.toPlainText()
        Xplot_title = self.ui.XtilTextEdit.toPlainText()
        Yplot_title = self.ui.YtilTextEdit.toPlainText()

        xpoint = self.ui.XTextEdit.toPlainText()
        ypoint = self.ui.YTextEdit.toPlainText()
        xpoints = np.array(list(map(int,xpoint.split( ))))
        ypoints = np.array(list(map(int,ypoint.split( ))))
        if xpoint and ypoint != '':
            self.gv_visual_data_content.fig1.plot(xpoints, ypoints,Line_shape)
            self.gv_visual_data_content.fig1.set_xlabel(Xplot_title,fontsize=12)
            self.gv_visual_data_content.fig1.set_ylabel(Yplot_title, fontsize=12)
            self.gv_visual_data_content.fig1.set_title(Plot_title,fontsize=12)#标题
            self.graphic_scene = QGraphicsScene()
            self.graphic_scene.addWidget(self.gv_visual_data_content)
            self.ui.graphicsView.setScene(self.graphic_scene)  # 把QGraphicsScene放入QGraphicsView
            self.ui.graphicsView.show()


            # self.ui.graphicsView.FullViewportUpdate
            # [1, 8], [3, 10]  # (1,3)-(8,10)
        else:  # x或y孔
            QMessageBox.warning(
                self.ui,
                '坐标错误',
                '请输入完整的x和y坐标')


    def plot_cos(self):
        x = np.arange(0, 2 * np.pi, np.pi / 100)
        y = np.cos(x)
        print('x', x)
        print('y', y)
        print(type(x))
        self.gv_visual_data_content.fig1.plot(x, y)  # 在加在的图形gv_visual_data_content中的子图fig1中画图
        self.gv_visual_data_content.fig1.set_title('cos()')  # 设置图名
        self.graphic_scene = QGraphicsScene()  # 创建一个QGraphicsScene
        # 加载的图形（FigureCanvas）不能直接放到graphicview控件中，必须先放到graphicScene，然后再把graphicscene放到graphicview中
        self.graphic_scene.addWidget(self.gv_visual_data_content)
        # 把图形放到QGraphicsScene中，注意：图形是作为一个QWidget放到放到QGraphicsScene中的
        self.ui.graphicsView.setScene(self.graphic_scene)  # 把QGraphicsScene放入QGraphicsView
        self.ui.graphicsView.show()  # 调用show方法呈现图形


if __name__ == "__main__":
    app = QApplication([])
    # 实例化窗口
    mainwindow = MainWindow()
    mainwindow.ui.show()
    app.exec_()
